package flexunit.sosui 
{
	import flexunit.framework.AssertionFailedError;
	import flexunit.framework.Test;
	import flexunit.framework.TestResult;
	import flexunit.runner.BaseTestRunner;	

	/**
	 * @author Wang Kang
	 */
	public class SosTestRunner extends BaseTestRunner
	{
		public static function run( test:Test ):TestResult
		{
			return new SosTestRunner().doRun(test);
		}

		public function SosTestRunner()
		{
			connector = new SosConnector();
			connector.send(SosConnector.RESULT, "Unit test begin:\n \n");
		}

		public override function testEnded( test:Test ):void
		{
			if( !currentTestFailed ) connector.send(SosConnector.PASSED, test.toString());
			currentTestFailed = false;	
			// ensure that the connector works after a failure or an error.
			if( ++currentTestCount == totalTestCount)
			{		
				var message:String = "";
				message += "\n◆ Total: " + totalTestCount;
				message += "\t◆ Failed: " + result.failureCount();				message += "\t◆ Errors: " + result.errorCount();
				connector.send(SosConnector.RESULT, message);
			}
		}

		public override function testError( test:Test, error:Error ):void
		{
			currentTestFailed = true;
			connector.send(SosConnector.FAILED, test.toString(), error);
		}

		public override function testFailure( test:Test, error:AssertionFailedError ):void 
		{
			currentTestFailed = true;
			connector.send(SosConnector.FAILED, test.toString(), error);
		}

		private function doRun( test:Test ):TestResult
		{
			result = new TestResult();
			result.addListener(this);
			totalTestCount = test.countTestCases();
			test.runWithResult(result);
			return result;
		}

		private var connector:SosConnector;
		private var result:TestResult;
		private var totalTestCount:int;		private var currentTestCount:int = 0;
		private var currentTestFailed:Boolean;
	}
}
